package com.utils
{
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	
	import mx.controls.Alert;

	public class FileWriter
	{
		public static var instance:FileWriter;
		private var _file:File;
		private var _xmlData:XML;
		private var _bmlData:ByteArray;
		private var _outPutFile:File;
		private var _fileList:Array;
		public function FileWriter(value:Singel)
		{
			_file = new File();
		}
		
		public static function getInstance():FileWriter
		{
			if (instance==null) {
				instance = new FileWriter(new Singel());
			}
			return instance;
		}
		/**
		 *写XML文件 
		 * @param xmlData
		 * 
		 */		
		public function saveXML(xmlData:XML):void
		{
			_xmlData = xmlData;
			_file.browseForSave("保存XML文件...");
			_file.addEventListener(Event.SELECT,onFileSelectedHandle);
		}
		
		private function onFileSelectedHandle(event:Event):void
		{
			_file.removeEventListener(Event.SELECT,	onFileSelectedHandle);
			var fileStream:FileStream = new FileStream();
			fileStream.openAsync(_file, FileMode.WRITE);
			fileStream.writeUTFBytes(_xmlData);
			fileStream.close();
			Alert.show("保存xml成功!");
		}
		
		public function saveByteArray(data:ByteArray):void
		{
			_bmlData = data;
			_file.browseForSave("保存压缩文件...");
			_file.addEventListener(Event.SELECT,onBMLFileSelectedHandle);
		}
		
		private function onBMLFileSelectedHandle(event:Event):void
		{
			_file.removeEventListener(Event.SELECT,onBMLFileSelectedHandle);
			
			var fileStream:FileStream = new FileStream();
			fileStream.openAsync(_file, FileMode.WRITE);
			fileStream.writeBytes(_bmlData);
			fileStream.close();
			Alert.show("保存压缩文件成功!");
		}
		
		
		public function saveFileByDirectory(list:Array):void
		{
			_fileList = list;
			_outPutFile = File.documentsDirectory;
			_outPutFile.addEventListener(Event.SELECT,onDirectorySelectHandle);
			_outPutFile.browseForDirectory("选择目录");
		}
		
		private function onDirectorySelectHandle(event:Event):void
		{
			_outPutFile.removeEventListener(Event.SELECT,onDirectorySelectHandle);
			
			var index:int=0;
			while(index<_fileList.length)
			{
				var file:File=new File(_outPutFile.nativePath+"/"+_fileList[index].fileName);
				var fileStream:FileStream=new FileStream();
				fileStream.open(file,FileMode.WRITE);
				fileStream.writeBytes(_fileList[index].data);
				fileStream.close();
				index++;
			}
			
			Alert.show("GZP文件解析保存完毕!");
		}
		
	}
}
class Singel
{
	
}